<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%@include file="/common/taglibs.jsp"%>
<%@include file="/common/meta.jsp"%>
<title>选择资源</title>
</head>
<body>

	<div style="padding-bottom: 10px;">
		当前角色：<c:out value="${role.roleName }"/>
		<input id="submit" type="button" value="保存"/>
	</div>
	<div id="resourceTree" class="ztree"></div>
	
	<script type="text/javascript">
		var setting = {
			async: {
				enable: true,
				url: "<c:url value='/pf/resource/ztree'/>"
			},
			callback: {
				onAsyncSuccess: zTreeOnAsyncSuccess,
				onAsyncError: zTreeOnAsyncError
			},
			check: {
				enable: true,
				chkStyle: "checkbox",
				chkboxType: {"Y": "p", "N": "p"}
			},
			data: {
				simpleData: {
					enable: true,
					rootPId: "-1"
				}
			},
			view: {
				selectedMulti: false
			}
		};
		
		//异步正常加载结束回调函数
		function zTreeOnAsyncSuccess(event, treeId, treeNode, msg) {
			var treeObj = $.fn.zTree.getZTreeObj(treeId);
			var nodes = treeObj.transformToArray(treeObj.getNodes());
			if (nodes.length > 0) {
				for(var i = 0; i < nodes.length; i++) {
					treeObj.expandNode(nodes[i]);
				}
			}
			
			var temp = new Array();
			$.post(
				"<c:url value='/pf/role/roleResourceZtree'/>",
				{"roleId": "${role.id}"},
				function(data, status) {
					if ("success" == status) {
						if (data.length > 0) {
							for(var j = 0; j < nodes.length; j++) {
								for(var i = 0; i < data.length; i++) {
									if(nodes[j].id == data[i].id) {
										temp.push(nodes[j]);
									}
								}
							}
							if(temp.length > 0) {
								for(var k = 0; k < temp.length; k++) {
									treeObj.checkNode(temp[k], true, true);
								}
							}
						}
					}
				}
			);
		}
		
		//异步异常加载回调函数
		function zTreeOnAsyncError(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) {
			console.log(treeId, treeNode, textStatus);
		}
		
		$(function() {
			$.fn.zTree.init($("#resourceTree"), setting, null);
			
			$("#submit").click(function() {
				var resourceIds = "";
				var treeObj = $.fn.zTree.getZTreeObj("resourceTree");
				var nodes = treeObj.getCheckedNodes(true);
				if(nodes.length > 0) {
					for(var i = 0; i < nodes.length; i++) {
						resourceIds += nodes[i].id + ",";
					}
				}
				if("" == resourceIds || resourceIds.length < 0) {
					art.dialog.alert("请选择资源进行保存!");
					return false;
				}
				
				$.post(
					"<c:url value='/pf/role/saveRoleResource'/>",
					{"roleId": "${role.id }", "resourceIds": resourceIds.substring(0, resourceIds.length - 1)},
					function(data, status) {
						if("success" == status) {
							parent.closeAndRefresh();
						} else {
							art.dialog.alert(data.msg);
						}
					}		
				);
			});
		});
	</script>
</body>
</html>